package com.pic.mgt.action;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

public abstract class AbstractMissUnitInspectActionImpl implements
		MissUnitInspectAction {
	
	protected boolean isIgnoreEmptyBizConfirmationFile;
	protected boolean isIgnoreEmptyMsgConfirmationFile;
	
	/**
	 * 根據給定的目錄,日期,容許時間和檢測的檔案類型,到目錄底下找尋檔案,如果檔案存在超過
	 * 指定的時間,就會被當作是miss掉的檔案.
	 * @param folder
	 * @param nowDate
	 * @param inspectionThteshold
	 * @param suffixFilenameFilter
	 * @return File[],陣列內所包含的 File 是存在超過容許時間的檔案;若回傳為 null表示沒有
	 */
	protected File[] checkFileMissUnderFolder(File folder,
										     Date nowDate,
										     long inspectionThteshold,
										     SuffixFilenameFilter suffixFilenameFilter) {
		
		List<File> needToRecoveryFileList = null;
		
		File[] checkFiles = folder.listFiles(suffixFilenameFilter);
		if (null != checkFiles) {
			for (File checkFile : checkFiles) {
				if (checkFile.isFile()) {
					boolean isFileExistedOverTime =
						this.isFileExistedOverTime(checkFile, nowDate, inspectionThteshold);
					if (isFileExistedOverTime) {
						// 表示檔案已存在超過設定的時間
						
						if (null == needToRecoveryFileList) {
							needToRecoveryFileList = new LinkedList<File>();
						}
						
						needToRecoveryFileList.add(checkFile);
					}
				}
			}
		}
		
		if (null == needToRecoveryFileList) {
			return null;
		}
		else {
			return
				needToRecoveryFileList.toArray(new File[needToRecoveryFileList.size()]);
		}
	}
	
	protected boolean isFileExistedOverTime(File checkFile, Date nowDate, long inspectionThteshold) {
		long lastModifiedTime = checkFile.lastModified();
		
		if (lastModifiedTime <= 0) {
			// 小於或等於零代表時間有問題(或已檔案不存在了),不處理
			return false;
		}
		
		long nowTime = nowDate.getTime();
		
		long timeDiff = nowTime - lastModifiedTime;
		if (timeDiff > inspectionThteshold) {
			return true;
		}
		else {
			return false;
		}
	}
	
	protected class SuffixFilenameFilter implements FilenameFilter {
		private String acceptFilenameSuffix;
		
		public SuffixFilenameFilter(String acceptFilenameSuffix) {
			this.acceptFilenameSuffix = acceptFilenameSuffix;
		}

		@Override
		public boolean accept(File dir, String name) {
			return
				name.endsWith(this.acceptFilenameSuffix);
		}
		
	}
	
	// --- getter and setter ---

	public void setIgnoreEmptyBizConfirmationFile(
			boolean isIgnoreEmptyBizConfirmationFile) {
		this.isIgnoreEmptyBizConfirmationFile = isIgnoreEmptyBizConfirmationFile;
	}

	public void setIgnoreEmptyMsgConfirmationFile(
			boolean isIgnoreEmptyMsgConfirmationFile) {
		this.isIgnoreEmptyMsgConfirmationFile = isIgnoreEmptyMsgConfirmationFile;
	}
}
